package com.w3cz.controller;

import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class WeChatAccessController {
	// 添加slf4j日志实例对象
	private final static Logger logger = LoggerFactory.getLogger(WeChatAccessController.class);
	
	@Value("#{wxProperties.token}")
	private String token;

	
	/**
	 * 只有微信接入的是get请求其他都是post请求
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 * @return
	 */
	@RequestMapping(value="/wechat",method=RequestMethod.GET)
	@ResponseBody
	public String wechat(String signature,String timestamp,String nonce,String echostr){
		//1）将token、timestamp、nonce三个参数进行字典序排序
		//2）将三个参数字符串拼接成一个字符串进行sha1加密
		//3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		
		boolean checkSignature = checkSignature(signature,  timestamp,  nonce);
		
		if(!checkSignature){
			logger.info("微信服务器配置错误...");
			return "fail";
		}
		
		System.out.println(echostr);
		return echostr;
	}

	/**
     * 方法名：checkSignature</br> 详述：验证签名</br> 开发人员：Damon</br> 创建时间：2017-07-11
     * </br>
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     * @throws
     */
    public boolean checkSignature(String signature, String timestamp, String nonce)
    {
        // 1.将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = new String[]
        { token, timestamp, nonce };
        Arrays.sort(arr);

        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++)
        {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;
        try
        {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }

        content = null;
        // 3.将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }

    /**
     * 方法名：byteToStr</br> 详述：将字节数组转换为十六进制字符串</br> 开发人员：Damon </br>
     * 创建时间：2017-07-11 </br>
     * @param byteArray
     * @return
     * @throws
     */
    private static String byteToStr(byte[] byteArray)
    {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++)
        {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 方法名：byteToHexStr</br> 详述：将字节转换为十六进制字符串</br> 开发人员：Damon</br>
     * 创建时间：2017-07-11 </br>
     * @param mByte
     * @return
     * @throws
     */
    private static String byteToHexStr(byte mByte)
    {
        char[] Digit =
        { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }


}
